package com.smtech.xz.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Administrator
 */
public class ImageUtils {

    public static final String PATH = "/oa/";
    private static ImageView showImageView;
    private static String mUrl;


    public static String getFileName(String url) {
        int index = url.lastIndexOf("/") + 1;
        return url.substring(index);
    }

    public static void setImageBitmap(String url, ImageView iv) {
        showImageView = iv;
        mUrl = url;
        Bitmap loacalBitmap = ImageUtils.getLoacalBitmap(Environment.getExternalStorageDirectory().getAbsolutePath() + ImageUtils.PATH + ImageUtils.getFileName(url));
        if (loacalBitmap != null) {
            showImageView.setImageBitmap(loacalBitmap);
            Log.d("ImageUtils", "本地获取");
        } else {
            Log.d("ImageUtils", "网络获取");
//            new DownImgAsyncTask().execute(url);
        }
    }


    /**
     * 通过URL地址获取Bitmap对象
     */
    public static Bitmap getBitmapByUrl(final String url) {
        URL fileUrl = null;
        InputStream is = null;
        Bitmap bitmap = null;
        try {
            fileUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            Log.d("shaoace", "1");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            is = null;
        }
        return bitmap;
    }

    /**
     * 保存图片到本地路径
     *
     * @param bmp
     * @param path
     * @param fileName
     * @return
     */
    public static File saveImage(Bitmap bmp, String path, String fileName) {

        File appDir = new File(path);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    public static void saveNewFile(Context context, File file, String path) {
        String fileParentPath = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH;

        File appDir = new File(fileParentPath);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        //获得原文件流
        FileInputStream fis = null;
        //输出文件流
        FileOutputStream fos = null;
        //目标文件
        File targetFile = new File(appDir, path);
        try {
            fis = new FileInputStream(file);
            fos = new FileOutputStream(targetFile);
            // 缓冲数组
            byte[] b = new byte[1024 * 8];
            while (fis.read(b) != -1) {
                fos.write(b);
            }
            fos.flush();
            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //扫描媒体库
        String extension = MimeTypeMap.getFileExtensionFromUrl(targetFile.getAbsolutePath());
        String mimeTypes = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        MediaScannerConnection.scanFile(context, new String[]{targetFile.getAbsolutePath()},
                new String[]{mimeTypes}, null);
    }


    /**
     * 删除旧图片
     */
    public static void seleteOldFile() {
        String fileParentPath = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH;
        File deleteFile = new File(fileParentPath);

        RecursionDeleteFile(deleteFile);
        if (!deleteFile.exists()) {
            deleteFile.mkdirs();
        }

    }

    /**
     * 递归删除文件和文件夹
     *
     * @param file 要删除的根目录
     */
    public static void RecursionDeleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                RecursionDeleteFile(f);
            }
            file.delete();
        }
    }

    /**
     * @Title: getLoacalBitmap * @Description: 加载本地图片 * @param @param url 本地路径 * @param @return * @return Bitmap * @throws
     */
    public static Bitmap getLoacalBitmap(String url) {
//        String fileParentPath = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH + url;

        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                // /把流转化为Bitmap图片
                return BitmapFactory.decodeStream(fis);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }


}
